#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 30 12:07:42 2020

@author: zeng
"""
import os 
import shutil
import linecache

#不同的编辑器默认当前目录不一样，请修改下行，指定linuxcmd 仓库的绝对路径。
os.chdir("/root/workdir/gitdir/linuxcmd")

#清空目录
try:
    shutil.rmtree('./html')
except FileNotFoundError:
    print("htm目录不存在，不用处理")
os.mkdir('./html')

#复制源文件
shutil.copyfile("./template/index.ejs", "./html/index.html")
shutil.copyfile("./template/list.ejs", "./html/list.html")
shutil.copytree("./template/js", "./html/js")
shutil.copytree("./template/img", "./html/img")
shutil.copytree("./template/css", "./html/css")
shutil.copytree("./template/source", "./html/source")

#创建 ./html/c 目录用来存放 linux命令批量生成的html网页
os.mkdir('./html/c')

txtList = os.listdir('./command')  #将该目录下的的所有文件名称存入列表txtList
txtList.sort()   # 显示当前文件夹下所有文件并进行排序
totalCmd = len(txtList)

cmdKeyDict = {} #将命令和命令的描述说明以字典的形式存放

for cmdTxt in txtList:
    #获取命令名称和描述说明，txt第1行命令名称，第3行命令的描述说明，以字典形式存放
    cmdKey = linecache.getline("./command/{0}".format(cmdTxt), 1).strip()
    cmdDescription = linecache.getline("./command/{0}".format(cmdTxt), 3).strip()
    cmdKeyDict[cmdKey] = cmdDescription
    #print(cmdKeyDict)
    
    header = open('./template/header.ejs', "r")
    footer = open('./template/footer.ejs', "r")
    search = open('./template/search.ejs', "r")
    modAddCmd = open('./template/modAddCmd.ejs', "r")
    
    
    cmd = open('./command/{0}'.format(cmdTxt), "r")
    cmdName = cmdTxt[:-4] #去掉 bg.txt 后缀 .txt

    html = open('./html/c/{0}.html'.format(cmdName), "w") 
    #打开列表中的文件,读取文件内容
    html.write(header.read())  #写入html文件中
    html.write(search.read())
    html.write(modAddCmd.read())
    html.write(cmd.read())
    html.write(footer.read())
    html.close()
    
    #替换一些指定字符串
    html = open('./html/c/{0}.html'.format(cmdName), "r") 
    lines = html.readlines()
    html.close()
    
    html = open('./html/c/{0}.html'.format(cmdName), "r+") 
    for l in lines:
        html.write(l.replace('cmdTxt', '{0}'.format(cmdTxt)).replace('totalCmd', '{0}'.format(totalCmd)).replace('cmdDescription', '{0}'.format(cmdDescription)).replace('cmdName', '{0}'.format(cmdName)).replace('enTxt', '{0}.en.txt'.format(cmdName)))
    html.close()    
    header.close()
    footer.close()
    search.close()
    modAddCmd.close()


#生成 hot.html
allUrl=[]
cmdKeys = list(cmdKeyDict.keys())
cmdKeys.sort()
for i,item in  enumerate(cmdKeys):
    li = '<li><a href="./c/' + cmdKeys[i] + ".html" +'">' + cmdKeys[i] + " " +"-" + " " + cmdKeyDict[cmdKeys[i]] + "</a></li>"
    allUrl.append(li)


hot2 = open('./template/hot2', 'w')
for ip in allUrl:
    hot2.write(ip)
    hot2.write('\n')
hot2.close()

#合并 hot1.ejs hot2 hot3.ejs
hot1 = open('./template/hot1.ejs', "r")
hot2 = open('./template/hot2', "r")
hot3 = open('./template/hot3.ejs', "r")

hotHtml = open('./html/hot.html', "w")
hotHtml.write(hot1.read())
hotHtml.write(hot2.read())
hotHtml.write(hot3.read())

hot1.close()
hot2.close()
hot3.close()
hotHtml.close()

#处理 index.html 对没有的html文件的命令标记删除线 <s> </s>
allKeys =['cat', 'chattr', 'chgrp', 'chmod', 'chown', 'cksum', 'cmp', 'diff', 'diffstat', 'filefind', 'file', 'find', 'git', 'gitview', 'indent', 'cut', 'ln', 'less', 'locate', 'lsattr', 'mattrib', 'mc', 'mdel', 'mdir', 'mktemp', 'more', 'mmove', 'mread', 'mren', 'mtools', 'mtoolstest', 'mv', 'od', 'paste', 'patch', 'rcp', 'rm', 'slocate', 'split', 'tee', 'tmpwatch', 'touch', 'umask', 'which', 'cp', 'whereis', 'mcopy', 'mshowfat', 'rhmask', 'scp', 'awk', 'col', 'colrm', 'comm', 'csplit', 'ed', 'egrep', 'ex', 'fgrep', 'fmt', 'fold', 'grep', 'ispell', 'jed', 'joe', 'join', 'look', 'mtype', 'pico', 'rgrep', 'sed', 'sort', 'spell', 'tr', 'expr', 'uniq', 'wc', 'lprm', 'lpr', 'lpq', 'lpd', 'bye', 'ftp', 'uuto', 'uupick', 'uucp', 'uucico', 'tftp', 'ncftp', 'ftpshut', 'ftpwho', 'ftpcount', 'cd', 'df', 'dirs', 'du', 'quotaoff', 'lndir', 'repquota', 'quotaon', 'tree', 'umount', 'ls', 'quotacheck', 'mmount', 'rmdir', 'rmt', 'stat', 'mzip', 'pwd', 'quota', 'mount', 'mkdir', 'mlabel', 'mmd', 'mrd', 'eject', 'mcd', 'mdeltree', 'mdu', 'badblocks', 'cfdisk', 'dd', 'e2fsck', 'ext2ed', 'fsck', 'fsck.minix', 'fsconf', 'fdformat', 'hdparm', 'mformat', 'mkbootdisk', 'mkdosfs', 'mke2fs', 'mkfs.ext2', 'mkfs.msdos', 'mkinitrd', 'mkisofs', 'mkswap', 'mpartition', 'swapon', 'symlinks', 'sync', 'mbadblocks', 'mkfs.minix', 'fsck.ext2', 'fdisk', 'losetup', 'mkfs', 'sfdisk', 'swapoff', 'edquota', 'apachectl', 'arpwatch', 'dip', 'getty', 'mingetty', 'uux', 'telnet', 'uulog', 'uustat', 'ppp-off', 'netconfig', 'nc', 'httpd', 'ifconfig', 'minicom', 'mesg', 'dnsconf', 'wall', 'netstat', 'ping', 'pppstats', 'samba', 'setserial', 'talk', 'traceroute', 'tty', 'newaliases', 'uuname', 'netconf', 'write', 'statserial', 'efax', 'pppsetup', 'tcpdump', 'ytalk', 'cu', 'smbd', 'testparm', 'smbclient', 'shapecfg', 'adduser', 'chfn', 'useradd', 'date', 'exit', 'finger', 'fwhios', 'sleep', 'suspend', 'groupdel', 'groupmod', 'halt', 'kill', 'last', 'lastb', 'login', 'logname', 'logout', 'ps', 'nice', 'procinfo', 'top', 'pstree', 'reboot', 'rlogin', 'rsh', 'sliplogin', 'screen', 'shutdown', 'rwho', 'sudo', 'gitps', 'swatch', 'tload', 'logrotate', 'uname', 'chsh', 'userconf', 'userdel', 'usermod', 'vlock', 'who', 'whoami', 'whois', 'newgrp', 'renice', 'su', 'skill', 'w', 'id', 'free', 'dnf', 'reset', 'clear', 'alias', 'dircolors', 'aumix', 'bind', 'chroot', 'clock', 'crontab', 'declare', 'depmod', 'dmesg', 'enable', 'eval', 'export', 'pwunconv', 'grpconv', 'rpm', 'insmod', 'kbdconfig','lilo', 'liloconfig', 'lsmod', 'minfo', 'set', 'modprobe', 'ntsysv', 'mouseconfig', 'passwd', 'pwconv','rdate', 'resize', 'rmmod', 'grpunconv', 'modinfo', 'time', 'setup', 'sndconfig', 'setenv', 'setconsole', 'timeconfig', 'ulimit', 'unset', 'chkconfig', 'apmd', 'hwclock', 'mkkickstart', 'fbset', 'unalias', 'SVGATextMode', 'ar', 'bunzip2', 'bzip2', 'bzip2recover', 'gunzip', 'unarj', 'compress', 'cpio', 'dump', 'uuencode', 'gzexe', 'gzip', 'lha', 'restore', 'tar', 'uudecode', 'unzip', 'zip', 'zipinfo', 'setleds', 'loadkeys', 'rdev', 'dumpkeys', 'MAKEDEV', 'bc']

index = open('./html/index.html', "r") 
lines = index.readlines()
index.close()

#替换hot.html中的变量
hothtml = open('./html/hot.html', "r") 
lines = hothtml.readlines()
html.close()
hothtml = open('./html/hot.html', "r+") 
for l in lines:
    hothtml.write(l.replace('totalCmd', '{0}'.format(totalCmd)))
hothtml.close() 

#替换list.html中的变量
listhtml = open('./html/list.html', "r") 
lines = listhtml.readlines()
listhtml.close()
listhtml = open('./html/list.html', "r+") 
for l in lines:
    listhtml.write(l.replace('totalCmd', '{0}'.format(totalCmd)))
listhtml.close()   

#替换index.html中的变量
indexhtml = open('./html/index.html', "r") 
lines = indexhtml.readlines()
indexhtml.close()
indexhtml = open('./html/index.html', "r+") 
for l in lines:
    indexhtml.write(l.replace('totalCmd', '{0}'.format(totalCmd)))
indexhtml.close()  



#对没有翻译的命令进行替换，生成下划线
def alter(file,old_str,new_str):
    """
    # https://blog.csdn.net/weixin_43400133/article/details/100067985
    将替换的字符串写到一个新的文件中，然后将原文件删除，新文件改为原来文件的名字
    :param file: 文件路径root
    :param old_str: 需要替换的字符串
    :param new_str: 替换的字符串
    :return: None
    """
    with open(file, "r", encoding="utf-8") as f1,open("%s.bak" % file, "w", encoding="utf-8") as f2:
        for line in f1:
            if old_str in line:
                line = line.replace(old_str, new_str)
            f2.write(line)
    os.remove(file)
    os.rename("%s.bak" % file, file)

for i,iterm1 in enumerate(allKeys):
    old = '>{0}<'.format(iterm1)
    new = '><s>{0}</s><'.format(iterm1)
    
    if iterm1 not in cmdKeys:
        
        alter('./html/index.html',old,new)
        #以下字符串不进行替换，不知道为什么。因此用上面的函数
        # index = open('./html/index.html', "r+")
        # for j,iterm3 in enumerate(lines):

        #     index.write(iterm3.replace(old, new))
        # index.close()

#生成 dt.js文件
dtjs = open('./html/js/dt.js', "w+") 

dtjs.write('var linux_commands = [')
dtjs.write('\n')  #插入一个换行符，格式化

for  idx,iterm in enumerate(cmdKeys):
    
    dtjs.write('{')
    dtjs.write('\n')
    
    dtjs.write('"n":"{0}",'.format(iterm))
    dtjs.write('\n')
    dtjs.write('"p":"/{0}",'.format(iterm))
    dtjs.write('\n')
    dtjs.write('"d":"{0}"'.format(cmdKeyDict[iterm]))
    dtjs.write('\n')
    dtjs.write('},')
    dtjs.write('\n')
    
dtjs.write(']')
dtjs.close()